import React from 'react'
import { Table, Popconfirm, Button } from 'antd'
import styles from './index.less'

const normalFn = () => {
}

export default (
  {
    dataSource = [],
    columns = [],
    total = 0,
    payload,
    loading = false,
    onEdit, // 触发编辑
    onRemove, // 删除
    changeStatus, // 更改状态
    onAdd, // 添加
    onChange = normalFn,
    rowKey = 'id',
    bordered = true,
  },
) => {
  // table属性
  const options = {
    dataSource, // 数据
    columns, // 表格配置
    loading,
    bordered, // 显示边框
    rowKey, // key
    onChange,
    pagination: { // 默认分页配置
      showTotal: (total) => `共${total}页 `,
      showSizeChanger: true,
    },
  }
  // 分页配置
  if (payload) {
    const {page, per_page} = payload
    options.pagination.total = total
    options.pagination.current = page
    options.pagination.pageSize = per_page
    options.pagination.showSizeChanger = per_page < 500
    options.pagination.showQuickJumper = total / per_page > 3
  }
  // 操作配置
  const actionsOptions = {
    title: '操作',
    dataIndex: 'action',
    render: (text, record) => (
      <div className={styles.action}>
        {onEdit && <strong onClick={() => onEdit(record)}>编辑</strong>}

        {changeStatus &&
        <strong onClick={() => changeStatus(record)}>{!record.status ? '禁用' : '启用'}</strong>}

        {onRemove &&
        <Popconfirm
          title="请确定是否删除?"
          onConfirm={() => onRemove(record)}
          okText="确定"
          cancelText="取消"
        > <strong>删除</strong>
        </Popconfirm>}
      </div>
    ),
  }
  if (onEdit && !columns.some(item => item.dataIndex === 'action')) {
    columns.push(actionsOptions)
  }

  return (
    <div>
      {onAdd && <Button onClick={onAdd} type='primary' style={{marginBottom: 20}}>添加</Button>}
      <Table {...options} />
    </div>
  )
}
